package org.lixf.io.utility;

import org.apache.commons.codec.binary.Base64;

import java.io.*;

public class IOUtility {

    public static String fileToBase64(String srcFile) {
        byte[] bytes = new byte[4 * 1024];
        String s = null;
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(srcFile));
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            int len;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            s = Base64.encodeBase64String(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    public static void base64ToFile(String base64String, String destFile) {
        try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile))) {
            os.write(Base64.decodeBase64(base64String));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 最慢
	/*
	private static void readWithIOException(String filePath) throws IOException {
		InputStream is = new FileInputStream(filePath);
		int b;
		while ((b = is.read()) != -1) {
			System.out.println(b);
		}
		is.close();
	}
	*/

    private static void copyFileByByteWithIOException(String srcFile, String destFile) throws IOException {
        byte[] bytes = new byte[4 * 1024];
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(srcFile));
             BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile))) {
            int len;
            while ((len = is.read(bytes)) != -1) {
                // must
                os.write(bytes, 0, len);
                os.flush();
            }
        }
    }

    private static void copyFileByByteLengthWithIOException(String srcFile, String destFile) throws IOException {
        byte[] bytes = new byte[4 * 1024];
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(srcFile));
             BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(destFile))) {
            int len;
            while ((len = is.read(bytes, 0, bytes.length)) != -1) {
                // must
                os.write(bytes, 0, len);
                os.flush();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String a = "a.txt";
        String b = "b.txt";
        String c = "c.txt";
        copyFileByByteLengthWithIOException(a, b);
        copyFileByByteWithIOException(a, c);
    }

}
